<template>
  <div class="daily-flow full-height bg-white content page-content relative-position" style="background-color: #fff; border-radius: 6px">
    <collapse ref="collapse" class="collapse-content after">
      <template v-slot:content>
        <yz-condition-filter
          @resetSearch="resetSearch"
          @onSubmit="onSubmit"
        >
          <div class="q-mr-md q-mb-sm">
            <span class="font-14" style="margin-right: 6px">生产日期:</span>
            <date-picker format="YYYY-MM-DD"
                         :clearable="false"
                         :editable="false"
                         range
                         v-model="queryParams.productDate"
                         placeholder="选择生产日期"
                         style="width: 220px"/>
          </div>
          <select-tooltip
            v-model="queryParams.workshop"
            :multiple="false"
            :options="workshopOpt"
            msg="所在车间"
          ></select-tooltip>
          <select-tooltip
            v-model="queryParams.processingDevice"
            isShowAll
            :options="processingDeviceOptions"
            msg="加工设备"
          ></select-tooltip>
          <fuzzy-search
            v-model="queryParams.product"
            class="margin-r-20"
            isFilter
            title="加工产品"
            :fuzzyFunc="fuzzyFunc"
            fuzzyValue="number"
          ></fuzzy-search>
          <yz-input
            v-model.trim="queryParams.productSpec"
            class="q-mr-md"
            title="产品规格"
          />
        </yz-condition-filter>
        <div class="left box form-inline">
          <q-btn class="btn margin-r-10"
                 outline
                 color="primary"
                 label="导出Excel"
                 :disable="!tableData.length"
                 @click="exportExcel"/>
        </div>
      </template>
    </collapse>
    <!--  table表格-->
    <q-table :data="tableData"
             :columns="tableColumns"
             row-key="indexId"
             style="margin-bottom: 62px"
             class="scroll myTable stick-first-2-col"
             separator="cell"
             :pagination.sync="pagination"
             :hide-bottom="tableData.length !== 0"
             :loading="tableLoading"
             color="primary">
      <template v-slot:header-cell-workDate="props">
        <q-th :props="props" style="width: 111px;min-width: 111px;z-index: 5">
          {{ props.col.label }}
        </q-th>
      </template>
      <template v-slot:header-cell-actualDuration="props">
        <q-th :props="props" style="min-width: 150px;z-index: 5">
          <div class="flex items-center">
            <div>{{ props.col.label }}</div>
            <tips class="margin-l-10" tips="实际换线时长 = 结束时间 - 开始时间 - 累计暂停时间。"/>
          </div>

        </q-th>
      </template>
      <template v-slot:body="props">
        <q-tr>
          <q-td class="td-padding" style="width: 111px;min-width: 111px">
            {{ props.row.workDate }}
          </q-td>
          <q-td class="td-padding">
            {{ props.row.deviceName }}
          </q-td>
          <q-td v-for="item in props.cols.length - 2" :key="item">
            <div v-if="props.row.shifts.length > 0">
              <div v-for="(shift, index) in props.row.shifts" :key="`shift${index}`">
                <div class="full-width bor-bottom item align-left td-padding" :class="{'border-top': index !== 0}" v-if="item < 2" :style="getColHeight(props.row, index)">
                  {{shift[props.cols[item+1].field] || '--' }}
                </div>
                <div v-else>
                  <div v-for="(workshopPlanning, planIndex) in shift.workshopPlannings" :key="planIndex">
                    <div v-if="item < 4" :style="{'height': (workshopPlanning.processPlannings.length > 0 ? tdHeight * workshopPlanning.processPlannings.length : tdHeight) + 'px!important'}" class="full-width bor-bottom item align-left td-padding" :class="{'border-top': index !== 0 || planIndex !== 0}">
                      {{ workshopPlanning[props.cols[item+1].field] || '--'}}
                    </div>
                    <div v-else-if="item === 4" :style="{'height': (workshopPlanning.processPlannings.length > 0 ? tdHeight * workshopPlanning.processPlannings.length : tdHeight) + 'px!important'}" class="full-width bor-bottom item align-left td-padding" :class="{'border-top': index !== 0 || planIndex !== 0}">
                      <td-spec :rowData="workshopPlanning"/>
                    </div>
                    <div v-else>
                      <div v-for="(processPlanningGroupItem, ppI) in workshopPlanning.processPlannings" :key="`processPlanningGroupItem${ppI}`">
                        <div :style="{'height': tdHeight + 'px!important'}"  class="full-width bor-bottom item align-left td-padding" :class="{'border-top': index!==0 || planIndex !== 0 || ppI !== 0}">
                          <span v-if="props.cols[item+1].field === 'pauseCount'" @click="onPauseCount(processPlanningGroupItem.timeRecords)" :style="{
                            color: props.cols[item+1].field === 'pauseCount' && processPlanningGroupItem.pauseCount  ? 'blue' : '',
                            cursor: 'pointer'
                          }">
                            {{processPlanningGroupItem.pauseCount}}
                          </span>
                          <span v-else>
                            {{processPlanningGroupItem[props.cols[item+1].field] === undefined ? '--' : processPlanningGroupItem[props.cols[item+1].field]}}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="full-width bor-bottom item align-left td-padding" v-else>--</div>
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <pagination v-model="pagination.page"
                :page-size="pagination.rowsPerPage"
                :total="pagination.rowsNumber"
                @changePageSize="onPageSizeChange"
                @changePage="onPageChange"
                style="margin-bottom: 20px" />
    <PauseCountDialog :show="isShowPauseCountDialog" @close=" isShowPauseCountDialog = false" :timeRecords="timeRecords"/>
  </div>
</template>

<script>
import Collapse from 'src/components/collapse'
import moment from 'moment'
import { getDeviceIds, getWorkshops } from '../../boot/job/process-order'
import { getSearchMaterials } from '../../boot/plan/plant-plan'
import Pagination from 'src/components/pagination'
import { getChangeoverReports, getChangeoverReportExport } from '../../boot/statistics/daily-flow'
import _ from 'lodash'
import { mapGetters } from 'vuex'
import PauseCountDialog from './pause-count-dialog'
export default {
  name: 'change-line-analysis',
  components: {
    Collapse,
    Pagination,
    PauseCountDialog
  },
  data () {
    return {
      fuzzyFunc: getSearchMaterials,
      queryParams: {
        productDate: [moment(new Date()).subtract(6, 'days').toDate(), new Date()],
        workshop: '',
        processingDevice: ['all'],
        product: ''
      },
      tableData: [],
      tableLoading: false,
      tableColumns: [
        { name: 'workDate', label: '生产日期', field: 'workDate', align: 'left' },
        { name: 'deviceName', label: '加工设备', field: 'deviceName', align: 'left' },
        { name: 'shiftName', label: '轮班', field: 'shiftName', align: 'left' },
        { name: 'workshopPlanningNumber', label: '计划编号', field: 'workshopPlanningNumber', align: 'left' },
        { name: 'productName', label: '加工产品 ', field: 'productName', align: 'left' },
        { name: 'productStandard', label: '产品规格 ', field: 'productStandard', align: 'left' },
        { name: 'processName', label: '加工工序 ', field: 'processName', align: 'left' },
        { name: 'operatorName', label: '操作员', field: 'operatorName', align: 'left' },
        { name: 'technicianName', label: '技术员', field: 'technicianName', align: 'left' },
        { name: 'cutterCount', label: '使用刀具数', field: 'cutterCount', align: 'left' },
        { name: 'estimatedDuration', label: '预计换线时长', field: 'estimatedDuration', align: 'left' },
        { name: 'totalDuration', label: '换线总时长', field: 'totalDuration', align: 'left' },
        { name: 'startTime', label: '换线开始时间', field: 'startTime', align: 'left' },
        { name: 'endTime', label: '换线结束时间', field: 'endTime', align: 'left' },
        { name: 'actualDuration', label: '实际换线时长', field: 'actualDuration', align: 'left' },
        { name: 'pauseDuration', label: '暂停时长', field: 'pauseDuration', align: 'left' },
        { name: 'pauseCount', label: '暂停次数', field: 'pauseCount', align: 'left' }
      ],

      workshopOpt: [],
      processingDeviceOptions: [],
      exportParams: {},
      // 表格分页配置
      pagination: {
        page: 1, // 当前页码
        rowsPerPage: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      timeRecords: '',
      isShowPauseCountDialog: false,
      tdHeight: 40 // 单元格高度
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  watch: {
    'queryParams.workshop': {
      immediate: true,
      handler: function (val) {
        if (val) {
          this.getDeviceIds()
        }
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    onPauseCount (timeRecords) {
      this.timeRecords = timeRecords
      this.isShowPauseCountDialog = true
    },
    init () {
      this.getWorkshops().then(() => {
        this.getTableData()
      })
    },
    // 查询表格数据
    getTableData () {
      if (!this.queryParams.workshop) {
        this.$message.warning('请选择所在车间')
        return
      }
      if (Math.abs(moment(this.queryParams.productDate[0]).diff(moment(this.queryParams.productDate[1]), 'days')) > 365) {
        this.$message.warning('日期范围不可超过一年')
        return
      }
      const params = {
        pageNum: this.pagination.page,
        pageSize: this.pagination.rowsPerPage,
        workshopId: this.queryParams.workshop,
        deviceIds: this.queryParams.processingDevice.indexOf('all') > -1 ? null : this.queryParams.processingDevice,
        startDate: moment(this.queryParams.productDate[0]).format('YYYY-MM-DD'),
        endDate: moment(this.queryParams.productDate[1]).format('YYYY-MM-DD'),
        productId: this.queryParams.product
      }
      this.queryParams.productSpec + '' !== '' && (params['productSpec'] = this.queryParams.productSpec)
      this.exportParams = _.cloneDeep(params)
      this.tableLoading = true
      getChangeoverReports(params).then(res => {
        this.pagination.rowsNumber = res.total
        this.tableData = res.list
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 导出excel
    exportExcel () {
      const selWorkshop = this.workshopOpt.find(item => item.value === this.queryParams.workshop)
      const exportParams = {
        workshopId: this.exportParams.workshopId,
        deviceIds: this.exportParams.deviceIds,
        startDate: this.exportParams.startDate,
        endDate: this.exportParams.endDate,
        productId: this.exportParams.productId,
        workshopName: selWorkshop.label
      }
      const params = [{ name: '换线分析统计' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      exportParams['requestId'] = res.fileNameNew
      this.onSubscribe()
      this.$q.loading.show()
      getChangeoverReportExport(exportParams).then(res => {
        if (res.code + '' !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUnsubscribeTopic()
        }
      }).catch(res => {
        this.closeUnsubscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUnsubscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, '换线分析统计.xls')
      this.closeUnsubscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    closeUnsubscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    // 获取加工车间
    getWorkshops () {
      return new Promise((resolve) => {
        getWorkshops().then(res => {
          this.workshopOpt = res.data
          if (this.workshopOpt && this.workshopOpt.length > 0) {
            this.queryParams.workshop = this.workshopOpt[0].value
            resolve()
          }
        })
      })
    },
    // 获取加工设备
    getDeviceIds () {
      const params = {}
      if (this.queryParams.workshop) {
        params['level'] = 2
        params['schemeId'] = this.queryParams.workshop
      } else {
        params['level'] = 0
      }
      getDeviceIds(params).then(res => {
        this.devicesMap = {}
        let devicesOption = []
        if (res.data.length) {
          res.data.forEach(item => {
            this.devicesMap[item.id] = item.name
            devicesOption.push({
              assetNumber: item.assetNumber,
              'label': `${item.name}(${item.assetNumber})`,
              'value': item.id
            })
          })
          this.queryParams.processingDevice = ['all']
        } else {
          this.queryParams.processingDevice = []
        }
        this.processingDeviceOptions = devicesOption
      })
    },
    /**
     * 计算单元格高度
     */
    getColHeight (row, index) {
      let count = 0
      if (row.shifts.length > 0) {
        const currentGroup = row.shifts[index].workshopPlannings
        if (currentGroup && currentGroup.length > 0) {
          currentGroup.forEach(item => {
            count += item.processPlannings.length
          })
        }
      } else {
        count = 1
      }
      return { 'height': this.tdHeight * count + 'px!important' }
    },
    // 查询按钮
    onSubmit () {
      this.pagination.page = 1
      this.getTableData()
    },
    // 重置按钮
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data().queryParams)
      if (this.workshopOpt && this.workshopOpt.length > 0) {
        this.queryParams.workshop = this.workshopOpt[0].value
      }
    },
    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.getTableData()
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.getTableData()
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .q-table thead tr th:first-child{
  z-index: 5;
  position: sticky;
  left: 0;
}
/deep/ .q-table thead tr th:nth-child(2){
  position: sticky;
  left: 111px;
  z-index: 5;
  border-right: 0;
  box-shadow: 3px 1px 3px rgba(0,0,0,0.1)
}
.stick-first-2-col {
  thead tr th:nth-child(2), tbody tr td:nth-child(2) {
    position: sticky;
    left: 111px;
    z-index: 3;
    border-right: 0;
    box-shadow: 3px 1px 3px rgba(0,0,0,0.1)
  }
  thead tr th:first-child, tbody tr td:first-child {
    position: sticky;
    left: 0;
    z-index: 3;
  }
}
/deep/ .q-table td{
  padding: 0;
}
.td-padding{
  padding: 0 16px!important;
}
.align-left {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.border-top {
  border-top: 1px solid #d3d3d3;
}
</style>
